<template>
  <div class="menu-management">
    <div class="menu-container">
      <!-- 左侧菜单树 -->
      <div class="menu-tree">
        <div class="tree-header">
          <h3>菜单树</h3>
        </div>
        <Tree
          v-if="treeData.length > 0"
          :data="treeData"
          :props="treeProps"
          height="calc(100vh - 200px)"
          @node-click="handleNodeClick"
        >
          <template #render-node="{ node }">
            <div class="tree-node">
              <Icon v-if="node.data.menuIcon" :icon="node.data.menuIcon" class="node-icon" />
              <span class="node-label">{{ node.data.menuName }}</span>
              <span class="node-type">{{ getMenuTypeText(node.data.menuType) }}</span>
            </div>
          </template>
        </Tree>

        <!-- 加载状态提示 -->
        <div v-else class="loading-state">
          <p>正在加载菜单数据...</p>
        </div>
      </div>

      <!-- 右侧详情 -->
      <div class="menu-detail">
        <div class="detail-header">
          <h3>菜单详情</h3>
          <div class="detail-actions">
            <BaseButton type="primary" @click="addMenu">新增菜单</BaseButton>
            <BaseButton type="primary" @click="saveMenu">保存</BaseButton>
            <BaseButton type="danger" @click="deleteMenu">删除</BaseButton>
          </div>
        </div>
        <div class="detail-content">
          <el-form
            v-if="currentMenu"
            ref="formRef"
            :model="currentMenu"
            :rules="formRules"
            label-width="100px"
            label-position="right"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="菜单名称" prop="menuName">
                  <el-input v-model="currentMenu.menuName" placeholder="请输入菜单名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="菜单编码" prop="menuCode">
                  <el-input
                    v-model="currentMenu.menuCode"
                    placeholder="请输入菜单编码"
                    @input="updateMenuRoute"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="所属父菜单" prop="menuParentId">
                  <el-tree-select
                    v-model="currentMenu.menuParentId"
                    :data="parentMenuTreeData"
                    :props="treeSelectProps"
                    :check-strictly="true"
                    placeholder="请选择父菜单"
                    style="width: 100%"
                    filterable
                    clearable
                    @change="updateMenuRoute"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="排序号" prop="ordinal">
                  <el-input-number
                    v-model="currentMenu.ordinal"
                    :min="0"
                    placeholder="请输入排序号"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="图标" prop="menuIcon">
                  <IconPicker v-model="currentMenu.menuIcon" :disabled="false" width="100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否启用" prop="isEnabled">
                  <el-switch
                    v-model="currentMenu.isEnabled"
                    :active-value="true"
                    :inactive-value="false"
                    active-text="启用"
                    inactive-text="禁用"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="打开方式" prop="openType">
                  <el-select
                    v-model="currentMenu.openType"
                    placeholder="请选择打开方式"
                    style="width: 100%"
                    clearable
                  >
                    <el-option
                      v-for="item in openTypeOptions"
                      :key="item.dictCode"
                      :label="item.dictName"
                      :value="item.dictCode"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <!-- 预留空间，保持布局美观 -->
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="菜单路径" prop="menuRoute">
                  <el-input v-model="currentMenu.menuRoute" placeholder="菜单路径" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input
                    v-model="currentMenu.remark"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入备注信息"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <!-- 空状态 -->
          <div v-else class="empty-detail">
            <p>请选择菜单或点击新增菜单</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import {
  ElMessage,
  ElMessageBox,
  ElForm,
  ElFormItem,
  ElInput,
  ElTreeSelect,
  ElInputNumber,
  ElSwitch,
  ElRow,
  ElCol,
  ElSelect,
  ElOption
} from 'element-plus'
import { Tree } from '@/components/Tree'
import { BaseButton } from '@/components/Button'
import { Icon } from '@/components/Icon'
import { IconPicker } from '@/components/IconPicker'
import {
  getSysMenuListApi,
  getSysMenuDetailApi,
  saveOrUpdateSysMenuApi,
  deleteSysMenuApi,
  type SysMenu,
  type MenuDTO
} from '@/api/system/menu'
// 使用新的字典工具
import { useDict } from '@/utils/dict'

// 响应式数据
const treeData = ref<MenuDTO[]>([])
const currentMenu = ref<SysMenu | null>(null)
const formRef = ref<InstanceType<typeof ElForm>>()
const parentMenuTreeData = ref<MenuDTO[]>([])
// 使用字典工具获取打开方式选项
const openTypeOptions = useDict('MENU_OPEN_TYPE')

// 树形配置
const treeProps = {
  children: 'children',
  label: 'menuName'
}

// 树选择器配置
const treeSelectProps = {
  children: 'children',
  label: 'menuName',
  value: 'menuId'
}

// 表单验证规则
const formRules = reactive({
  menuName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  menuCode: [{ required: true, message: '请输入菜单编码', trigger: 'blur' }],
  ordinal: [{ required: true, message: '请输入排序号', trigger: 'blur' }]
})

// 更新菜单路径
const updateMenuRoute = () => {
  if (!currentMenu.value) return

  nextTick(() => {
    const { menuCode, menuParentId } = currentMenu.value!

    if (!menuCode) {
      currentMenu.value!.menuRoute = ''
      return
    }

    if (!menuParentId || menuParentId === 0) {
      // 顶级菜单
      currentMenu.value!.menuRoute = `/${menuCode}`
    } else {
      // 子菜单，需要找到父菜单的路径
      const parentMenu = findParentMenu(menuParentId)
      if (parentMenu) {
        currentMenu.value!.menuRoute = `${parentMenu.menuRoute}/${menuCode}`
      } else {
        currentMenu.value!.menuRoute = `/${menuCode}`
      }
    }
  })
}

// 查找父菜单
const findParentMenu = (parentId: number): MenuDTO | null => {
  const findInTree = (nodes: MenuDTO[]): MenuDTO | null => {
    for (const node of nodes) {
      if (node.menuId === parentId) {
        return node
      }
      if (node.children && node.children.length > 0) {
        const found = findInTree(node.children)
        if (found) return found
      }
    }
    return null
  }

  return findInTree(treeData.value)
}

// 获取菜单类型文本
const getMenuTypeText = (type: number | string) => {
  const typeMap: Record<string | number, string> = {
    0: '目录',
    1: '菜单',
    2: '按钮'
  }
  return typeMap[type] || '未知'
}

// 加载菜单数据
const loadMenuData = async () => {
  try {
    const res = await getSysMenuListApi()
    treeData.value = res.data || []

    // 更新父菜单树数据（排除当前编辑的菜单）
    updateParentMenuTreeData()
  } catch (error) {
    console.error('加载菜单数据失败:', error)
    ElMessage.error('加载菜单数据失败')
  }
}

// 更新父菜单树数据
const updateParentMenuTreeData = () => {
  parentMenuTreeData.value = JSON.parse(JSON.stringify(treeData.value))
}

// 节点点击事件
const handleNodeClick = async (data: MenuDTO) => {
  try {
    if (data.menuId) {
      const res = await getSysMenuDetailApi(data.menuId)
      // 使用 Object.assign 处理接口返回数据，确保响应式
      currentMenu.value = Object.assign({}, res.data || {})
    } else {
      currentMenu.value = { ...data }
    }
    updateParentMenuTreeData()
  } catch (error) {
    console.error('获取菜单详情失败:', error)
    ElMessage.error('获取菜单详情失败')
  }
}

// 新增菜单
const addMenu = () => {
  currentMenu.value = {
    menuName: '',
    menuCode: '',
    menuRoute: '',
    menuParentId: undefined,
    menuType: '1',
    menuIcon: '',
    ordinal: 0,
    isEnabled: true,
    openType: undefined,
    remark: ''
  }
  updateParentMenuTreeData()
}

// 保存菜单详情
const saveMenu = async () => {
  // 如果没有选择菜单，创建一个新的菜单对象
  if (!currentMenu.value) {
    currentMenu.value = {
      menuName: '',
      menuCode: '',
      menuRoute: '',
      menuParentId: undefined,
      menuType: '1',
      menuIcon: '',
      ordinal: 0,
      isEnabled: true,
      openType: undefined,
      remark: ''
    }
  }

  try {
    const formInstance = formRef.value
    if (formInstance) {
      await formInstance.validate()
    }

    await saveOrUpdateSysMenuApi(currentMenu.value)
    ElMessage.success(currentMenu.value.menuId ? '菜单更新成功' : '菜单新增成功')

    // 重新加载数据，但保持当前编辑状态
    const currentMenuId = currentMenu.value.menuId
    await loadMenuData()

    // 如果是编辑模式，重新获取当前菜单的详细信息
    if (currentMenuId) {
      try {
        const res = await getSysMenuDetailApi(currentMenuId)
        currentMenu.value = Object.assign({}, res.data || {})
      } catch (error) {
        console.error('重新获取菜单详情失败:', error)
      }
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 删除菜单
const deleteMenu = async () => {
  if (!currentMenu.value?.menuId) {
    ElMessage.warning('请先选择要删除的菜单')
    return
  }

  try {
    await ElMessageBox.confirm('确定要删除这个菜单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteSysMenuApi(currentMenu.value.menuId)
    ElMessage.success('删除成功')

    // 重新加载数据
    await loadMenuData()
    currentMenu.value = null
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 初始化
onMounted(async () => {
  await loadMenuData()
  // 不再需要手动加载字典数据，useDict 会自动处理
  // 默认进入新增菜单模式
  addMenu()
})
</script>

<style lang="less" scoped>
.menu-management {
  height: 100%;
  padding: 16px;

  .menu-container {
    display: flex;
    height: 100%;
    gap: 16px;

    .menu-tree {
      width: 300px;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      background: #fff;

      .tree-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 16px;
        border-bottom: 1px solid #e4e7ed;

        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 500;
        }
      }

      .tree-node {
        display: flex;
        align-items: center;
        gap: 8px;

        .node-icon {
          font-size: 16px;
        }

        .node-label {
          flex: 1;
        }

        .node-type {
          font-size: 12px;
          color: #909399;
          background: #f5f7fa;
          padding: 2px 6px;
          border-radius: 2px;
        }
      }

      .loading-state {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 200px;
        color: #909399;

        p {
          margin: 0;
          font-size: 14px;
        }
      }
    }

    .menu-detail {
      flex: 1;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      background: #fff;

      .detail-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 16px;
        border-bottom: 1px solid #e4e7ed;

        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 500;
        }

        .detail-actions {
          display: flex;
          gap: 8px;
        }
      }

      .detail-content {
        padding: 16px;
      }

      .empty-detail {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 400px;
        color: #909399;

        p {
          margin: 16px 0 0 0;
          font-size: 14px;
        }
      }
    }
  }
}
</style>
